﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WordSmith_V1.ViewModel;
using WordSmith_V1.Library.Model;
using WordSmith_V1.Library.Model.EntityFrameWork;
using System.Data.Entity;

namespace WordSmith_V1.Controllers
{
    [Authorize]
    public class BookController : Controller
    {
        private WordSmithContext DB = new WordSmithContext();
        //
        // GET: /Book/

        public ActionResult Index(int bookId)
        {
            var book = DB.Books.Where(bk => bk.BookId == bookId).Include(bk => bk.Chapters).Include(bk=>bk.Authors).FirstOrDefault();//"Chapters").Include("Users");
            BookSummaryViewModel viewModel = new BookSummaryViewModel();
            viewModel.Book = book;
            viewModel.GenreName = "Test";
            return View(viewModel);
        }

        //
        // GET: /Book/Details/5

        public ActionResult Details(int id)
        {
            ChapterSummaryViewModel viewModel = new ChapterSummaryViewModel();
            string userEmail = HttpContext.User.Identity.Name;
            var user = DB.Users.Where(usr => usr.Email == userEmail).Take(1).ToList().FirstOrDefault();
            User Author = new User();
            Author = user;
            viewModel.Author = Author;

            var chap = DB.Chapters.Where(chp => chp.ChapterId == id).Take(1).ToList().FirstOrDefault();
            Chapter chapter = new Chapter();
            chapter = chap;
            viewModel.Chapter = chapter;

            var book = DB.Books.Where(bk => bk.BookId == chapter.BookId).Take(1).ToList().FirstOrDefault();
            Book newBook = new Book();
            newBook = book;
            viewModel.Book = newBook;

            var tags = DB.Tags.Where(tg => tg.ChapterId == chapter.ChapterId).ToList();
            List<Tag> tgs = new List<Tag>();
            tgs = tags;
            viewModel.Tag = tgs;

            var dbGenre = DB.Genres.Where(gnr => gnr.Id == newBook.GenreId).Take(1).ToList().FirstOrDefault();
            viewModel.Genre = dbGenre.Name;


            //user image
            //chapter details with edit link
            return View(viewModel);
        }
        
    /*    public ActionResult Details(BookChapterViewModel viewModel)
        {
            //user image
            //chapter details with edit link
            return View(viewModel);
        }
        */

        //
        // GET: /Book/Create

        public ActionResult Create()
        {
            BookChapterCreateViewModel viewModel = new BookChapterCreateViewModel();
            //List<Genre> genres = new List<Genre>();
            var genres = DB.Genres.Where(gen => gen.Id >= 1).ToList();
            IEnumerable<SelectListItem>  dropdownGenres= genres.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name.ToString() });
          /*  List<Interest> genres = new List<Interest>();
            genres.Add(new Interest(1,"Arts & Photography"));
            genres.Add(new Interest(2,"Biographies & Memoirs"));
            genres.Add(new Interest(3,"Business & Investing"));
            genres.Add(new Interest(4,"Comics & Graphic Novels"));
            genres.Add(new Interest(5,"Computers & Internet"));
           * */
            //READ MORE:MVC MOdel binding dropdown list http://stackoverflow.com/questions/5141714/model-binding-dropdown-selected-value
            //anohter good source
           // viewModel.selectedGenre = new Interest(0, "Please Select a genre");
            
            ViewBag.genreList = dropdownGenres;//viewModel.Genres;
           // viewModel.Genres = genres;
            return View(viewModel);
        } 

        //
        // POST: /Book/Create

        [HttpPost]                                                  //to be used later
        public ActionResult Create( BookChapterCreateViewModel viewModel,bool saveAndContinue = false)//FormCollection collection)
        {
            try
            {
                string userEmail = HttpContext.User.Identity.Name;
                var user = DB.Users.Where( usr => usr.Email == userEmail).Take(1).ToList().FirstOrDefault();
                if (user != null)
                {
                    //var selecteGenre = viewModel.selectedGenre;                   

                    viewModel.Author = user;
                    
                    string s = viewModel.Description;
                    
                    Book newBk = CreateBook(viewModel);
                    
                    Chapter chp = CreateChapter(viewModel, user.Id);
                    
                    //Add new book with new chapter                                      
                    
                    newBk.Chapters.Add(chp);                   
                    DB.Books.Add(newBk);
                    DB.SaveChanges();
                   // int newBkID = newBk.BookId;
                    // add book's chapter
                    //chp.BookId = newBkID;
                    //DB.Chapters.Add(chp);
                    //DB.SaveChanges();
                    int newChpID = chp.ChapterId;
                    //add chapter tags
                    CreateAndSaveTags(newChpID,viewModel.Tags);
                 
                  //  if (newChpID == 0)
                 //   {
                      return RedirectToActionPermanent("Details", new { id = newChpID });
                  //  }
                  //  else
                  //  {
                 //   return RedirectToAction("Details", new { viewModel = viewModel });
                    //}
 

                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            catch
            {
                return View(viewModel);
            }
        }

        private Book CreateBook(BookChapterCreateViewModel viewModel)
        {
            Book newBk = new Book();
            newBk.Title = viewModel.BookTitle;
            newBk.Image = viewModel.CoverImage ?? ""; //temporarily use the first chapter image as the book image
            newBk.GenreId = Int32.Parse(viewModel.selectedGenre);
            newBk.Authors.Add(viewModel.Author);
            return newBk;
        }

        private Chapter CreateChapter(BookChapterCreateViewModel viewModel,int userId)
        {
            Chapter chp = new Chapter();
            chp.Description = viewModel.Description;
            chp.Title = viewModel.ChapterTitle;
            chp.Writing = viewModel.Writing;
            chp.AuthorId = userId;
            chp.CoverImage = viewModel.CoverImage?? "";
            chp.EmailMe = true;
            chp.CreateDate = DateTime.Now;
            chp.UpdateDate = DateTime.Now;
            chp.StatusId = (int)Status.StatusType.PENDING;
            return chp;
        }

        private void CreateAndSaveTags(int chapterId, string tagStr)
        {
            char[] delimiter =  { ',' };
            string[] tags = tagStr.Split(delimiter);
            foreach (var tag in tags)
            {
                Tag newTag = new Tag(chapterId,tag);
                DB.Tags.Add(newTag);
                DB.SaveChanges();
            }
         
        }

        //
        // GET: /Book/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Book/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Book/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Book/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
